package com.briup.pts.service.impl;

import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.property.QiniuProperty;
import com.briup.pts.service.UploadService;
import com.briup.pts.utils.FileUtil;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

// 当一个接口出现多个实现类时，可以在其中一个类上添加@Primary注解，表示优先注入该注解标识类的bean对象
//@Primary
@Slf4j
@ConditionalOnBean(QiniuProperty.class)
@Service
@RequiredArgsConstructor
public class QiniuUploadServiceImpl implements UploadService {

    private final QiniuProperty qiniuProperty;

    @Override
    public String upload(MultipartFile file) {
        log.info("本次要上传的文件为:{}", file.getOriginalFilename());
        // 获取认证凭证
        Auth auth = Auth.create(qiniuProperty.getAccessKey(),
                qiniuProperty.getSecretKey());
        // 通过认证凭证 获取指定bucket空间中的 上传凭证
        String upToken = auth.uploadToken(qiniuProperty.getBucketName());

        //构造一个带指定Region对象的配置类，自动选择区域
        Configuration cfg = new Configuration(Region.autoRegion());
        // 根据配置获取 文件上传管理其
        UploadManager uploadManager = new UploadManager(cfg);
        // 生成文件在OSS云存储中的文件名字
        String key = FileUtil.generatorFileName(
                Objects.requireNonNull(file.getOriginalFilename()));
        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null);
        } catch (IOException e) {
            log.error("文件上传失败:", e);
            throw new ServiceException("文件上传失败，原因:" + e.getMessage());
        }

        // 上传成功，返回对应的url地址
        return String.format(qiniuProperty.getBaseUrl(),key);
    }
}
